import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Input, Popover} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT, FILES_API, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {injectIntl, language} from './intl';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import styles from './style.css';
import WrappedSelect from '../common/WrappedSelect';
import Return from '../common/Return';
import {approveValidator} from './validator';
import {getDetail} from './api';
import {partClaimType, currency, partClaimReasonStatus, partPaymentMethod} from '../Enum';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const {Description} = DescriptionList;

const FormItem = Form.Item;
const paymentMethodList = partPaymentMethod.toList(language);
class ApprovePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        details: []
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id)
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: res.data,
                            details: res.data.details
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmitRefuse = () => {
        const {data} = this.state;
        this.setState({loading: true});
        this.props.onSubmitRefuse(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSubmitReject = () => {
        const {data} = this.state;
        this.setState({loading: true});
        this.props.onSubmitReject(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSubmitPass = () => {
        const {data} = this.state;
        const isValid = approveValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmitPass(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading} = this.state;
        const validatePaymentMethod = !data.paymentMethod && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.approve, this.props.permissions);
        let claimFee = 0;
        let claimAmount = 0;
        if(details.length > 0)
            details.forEach(v => {
                claimFee += v.claimFee;
                claimAmount += v.claimAmount;
            });
        const colums = [{
            title: formatMessage({
                id: 'approvePanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partSaleOrderCode',
                defaultMessage: '备件销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.quantity',
                defaultMessage: '销售数量'
            }),
            dataIndex: 'quantity',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.price',
                defaultMessage: '备件单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.claimAmount',
                defaultMessage: '索赔数量'
            }),
            dataIndex: 'claimAmount'
        }, {
            title: formatMessage({
                id: 'approvePanel.column.claimFee',
                defaultMessage: '索赔金额'
            }),
            dataIndex: 'claimFee',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.claimReason',
                defaultMessage: '索赔原因'
            }),
            dataIndex: 'claimReason',
            render: text => conventEnumValueToString(partClaimReasonStatus, text)
        }, {
            title: this.props.intl.formatMessage({
                id: 'commonDetail.column.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'action',
            render: (text, record) => {
                const {attachments = []} = record;
                if(!attachments.length)
                    return '';
                const fileList = attachments.map(item => (<Description key={item.fileId}><a icon="download" href={`${FILES_API.files}/${item.fileId}`} size="small">
                    {item.fileName}</a></Description>));
                return (<Popover trigger="click" content={<DescriptionList col={1} size="large">
                    {fileList}
                </DescriptionList>}>
                    <a icon="download" size="small">
                        {this.props.intl.formatMessage({
                            id: 'add.downloadFile',
                            defaultMessage: '下载附件'
                        })}</a>
                </Popover>);
            }
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'approvePanel.column.common',
                        defaultMessage: '订单基本信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.code',
                                        defaultMessage: '编号'
                                    })}
                                    {...FORM_OPTIONS.item} >
                                        <Input placeholder={formatMessage({
                                            id: 'approvePanel.operation.notGenerate',
                                            defaultMessage: '尚未生成'
                                        })} value={data.code} disabled />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'approvePanel.operation.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {(data.brandCode) + data.brandName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.invoiceCode',
                                        defaultMessage: '发票号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.invoiceCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'approvePanel.operation.paymentMethod',
                                            defaultMessage: '赔付方式'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validatePaymentMethod}
                                        required>
                                        <WrappedSelect
                                            allowClear
                                            name="paymentMethod"
                                            value={data.paymentMethod}
                                            options={paymentMethodList}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'approvePanel.operation.claimType',
                                            defaultMessage: '索赔类型'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(partClaimType, data.claimType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'approvePanel.form.receiptDate',
                                            defaultMessage: '收货日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.receiptDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.dealerCode',
                                        defaultMessage: '总代编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.dealerName',
                                        defaultMessage: '总代名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.address',
                                        defaultMessage: '地址'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.address}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.contactNumber',
                                        defaultMessage: '联系电话'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.contactNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'approvePanel.form.createTime',
                                            defaultMessage: '提报日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.createTime, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.claimAmount',
                                        defaultMessage: '索赔总数量'
                                    })} {...FORM_OPTIONS.item}>
                                        {claimAmount}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.claimFee',
                                        defaultMessage: '索赔总金额'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatAmount(claimFee)}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item} >
                                        {data.remark}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.operation.detail',
                            defaultMessage: '订单清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="partId"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            onClick={this.onSubmitRefuse}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onSubmitRefuse',
                                defaultMessage: '拒赔'
                            })}
                        </Button>
                        <Button
                            onClick={this.onSubmitReject}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onSubmitReject',
                                defaultMessage: '驳回'
                            })}
                        </Button>
                        <Button
                            type="primary"
                            onClick={this.onSubmitPass}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onSubmitPass',
                                defaultMessage: '审核通过'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ApprovePanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmitPass: PropTypes.func.isRequired,
    onSubmitRefuse: PropTypes.func.isRequired,
    onSubmitReject: PropTypes.func.isRequired,
    enterprise: PropTypes.object,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onPass,
    onReject,
    onRefuse
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);

const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getEnterprise = selectorFactory(['page', 'domainData', 'initData', 'enterprise']);
const mapStateToProps = (state, props) => ({
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    permissions: getPermissions(state),
    initEnum: getinitEnumData(state),
    enterprise: getEnterprise(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmitPass: data => dispatch(onPass(data)),
    onSubmitReject: data => dispatch(onReject(data)),
    onSubmitRefuse: data => dispatch(onRefuse(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ApprovePanel));
